package net.dgg.zz.production.all.controller;

import net.dgg.common.tools.exception.ExceptionUtils;
import net.dgg.framework.tac.utils.bean.DggRestResponse;
import net.dgg.framework.tac.utils.web.commmon.DggBaseController;
import net.dgg.iboss.base.entity.uc.CustomerDTO;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.service.UcApiService;
import net.dgg.iboss.base.util.CustomerNumberEncryptionUtil;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.iboss.base.util.datatable.DataTableUtils;
import net.dgg.iboss.base.util.datatable.domain.DataTableRequest;
import net.dgg.iboss.base.util.datatable.domain.DataTableResponse;
import net.dgg.iboss.base.util.poi.ExcelUtil;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.datapermission.entity.DataAuthDTO;
import net.dgg.tmd.foundation.platform.datapermission.service.DataPermissionAssocService;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.tmd.foundation.platform.user.service.UserService;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.service.CommonMangerExtService;
import net.dgg.zz.common.utils.DateUtils;
import net.dgg.zz.common.utils.OrderHandleUtils;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.common.utils.excel.ExcelUtils;
import net.dgg.zz.flownode.dao.ZzProductNodeDao;
import net.dgg.zz.flownode.dao.ZzProductNodeFlowDao;
import net.dgg.zz.production.all.service.AllOrderService;
import net.dgg.zz.production.completed.service.ZzCompletedOrderService;
import net.dgg.zz.production.excption.ProductOrderExcption;
import net.dgg.zz.production.inProcess.entity.ProductNode;
import net.dgg.zz.production.inProcess.entity.ProductNodeFlow;
import net.dgg.zz.production.org.service.OrgOrderService;
import net.dgg.zz.production.vo.OrderCountVo;
import net.dgg.zz.production.vo.OrderDataVo;
import net.dgg.zz.production.vo.OrgOrderVo;
import net.fblock.log.NLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 所有订单
 * <p>@Package: net.dgg.zz.production</p>
 * <p>@Title：AllOrderController</p>
 * <p>@description:</p>
 * <p>@author liulei</p>
 * <p>@date 2018年8月27日</p>
 * <p>@Company dgg</p>
 */
@Controller
@RequestMapping("sc/all")
public class AllOrderController extends DggBaseController {


    @Autowired
    private AllOrderService allorderservice;
    @Autowired
    private DataPermissionAssocService dataPermissionAssocService;
    @Autowired
    private TranslateUtil translateUtil;

    @Autowired
    private CommonMangerExtService zzCommonMangerExtService;

    @Autowired
    private DesUtil desUtil;

    @Autowired
    private ZzProductNodeFlowDao zzProductNodeFlowDao;

    @Autowired
    private ZzProductNodeDao zzProductNodeDao;

    @Autowired
    private SessionManager sessionManager;

    @Autowired
    private OrgOrderService orgOrderService;
    @Autowired
    private CommonMangerExtService commonMangerExtService;
    @Autowired
    private UcApiService ucApiService;
    @Autowired
    private ZzCompletedOrderService zzCompletedOrderService;

    /**
     * 已分配分配订单列表
     *
     * @param model
     * @param status 状态
     * @return
     */
    @NLog
    @RequestMapping(value = "/allocatedScOrder")
    public String allocatedScOrder(Model model, String status) {
        return "zzsc/all/allocatedScOrder";
    }

    /**
     * 我的生产订单
     *
     * @param model
     * @param status 状态
     * @return
     */
    @NLog
    @RequestMapping(value = "/myScOrder")
    public String myScOrder(Model model, String status) {
        model.addAttribute("TIME_OUT", ScProductConstant.TIME_OUT);
        return "zzsc/all/myScOrder";
    }

    @NLog
    @RequestMapping(value = "/production_configuration")
    public String certificateProductionConfiguration(Model model, String status) {
        model.addAttribute("TIME_OUT", ScProductConstant.TIME_OUT);
        return "zzsc/all/production_configuration";
    }



    /**
     * 部门订单列表
     *
     * @param model
     * @param status 状态
     * @return
     */
    @NLog
    @RequestMapping(value = "/deptScOrder")
    public String deptScOrder(Model model, String status) {
        List<ProductNode> listNode = new ArrayList<>();
        //查询出当前登陆人的事业部id
        Map orgMap = zzCommonMangerExtService.findBusDeptById(sessionManager.getCurrentUser().getOrgId());
        if (orgMap != null && orgMap.size() != 0) {
            Map map = new HashMap();
            Map mapNode = new HashMap();
            StringBuilder ids = new StringBuilder();
            //根据事业部的id查询出改事业部配置流程节点ids
            map.put("deptIds", orgMap.get("id"));
            if (null == map.get("orderColumn")) {
                map.put("orderDir", "desc");
                map.put("orderColumn", "updateTime");
            }
            List<ProductNodeFlow> productNodeFlowList = zzProductNodeFlowDao.query(map);
            if (productNodeFlowList.size() > 0) {
                for (ProductNodeFlow productNodeFlow : productNodeFlowList) {
                    if (ids.length() > 0) {//该步即不会第一位有逗号，也防止最后一位拼接逗号！
                        ids.append(",");
                    }
                    ids.append(productNodeFlow.getId());
                }
                mapNode.put("deptIds", orgMap.get("id"));
                mapNode.put("processId", ids.toString().split(","));
                listNode = zzProductNodeDao.queryByFlowProcessIds(mapNode);
            }
        }
        model.addAttribute("listNode", listNode);
        model.addAttribute("TIME_OUT", ScProductConstant.TIME_OUT);
        return "zzsc/all/deptScOrder";
    }

    /**
     * 全部订单列表
     *
     * @param model
     * @param status 状态
     * @return
     */
    @NLog
    @RequestMapping(value = "/allScOrder")
    public String allScOrder(Model model, String status) {
        List<ProductNode> listNode = new ArrayList<>();
        //查询出当前登陆人的事业部id
        Map orgMap = zzCommonMangerExtService.findBusDeptById(sessionManager.getCurrentUser().getOrgId());
        if (orgMap != null && orgMap.size() != 0) {
            Map map = new HashMap();
            Map mapNode = new HashMap();
            StringBuilder ids = new StringBuilder();
            //根据事业部的id查询出改事业部配置流程节点ids
            map.put("deptIds", orgMap.get("id"));
            if (null == map.get("orderColumn")) {
                map.put("orderDir", "desc");
                map.put("orderColumn", "updateTime");
            }
            List<ProductNodeFlow> productNodeFlowList = zzProductNodeFlowDao.query(map);
            if (productNodeFlowList.size() > 0) {
                for (ProductNodeFlow productNodeFlow : productNodeFlowList) {
                    if (ids.length() > 0) {//该步即不会第一位有逗号，也防止最后一位拼接逗号！
                        ids.append(",");
                    }
                    ids.append(productNodeFlow.getId());
                }
                mapNode.put("deptIds", orgMap.get("id"));
                mapNode.put("processId", ids.toString().split(","));
                listNode = zzProductNodeDao.queryByFlowProcessIds(mapNode);
            }
        }
        model.addAttribute("listNode", listNode);
        model.addAttribute("TIME_OUT", ScProductConstant.TIME_OUT);
        return "zzsc/all/allScOrder";
    }
    /**
     * 终止订单列表
     *
     * @param model
     * @return
     */
    @NLog
    @RequestMapping(value = "/stopScOrder")
    public String stopScOrder(Model model) {
        List<ProductNode> listNode = new ArrayList<>();
        //查询出当前登陆人的事业部id
        Map orgMap = zzCommonMangerExtService.findBusDeptById(sessionManager.getCurrentUser().getOrgId());
        if (orgMap != null && orgMap.size() != 0) {
            Map map = new HashMap();
            Map mapNode = new HashMap();
            StringBuilder ids = new StringBuilder();
            //根据事业部的id查询出改事业部配置流程节点ids
            map.put("deptIds", orgMap.get("id"));
            if (null == map.get("orderColumn")) {
                map.put("orderDir", "desc");
                map.put("orderColumn", "updateTime");
            }
            List<ProductNodeFlow> productNodeFlowList = zzProductNodeFlowDao.query(map);
            if (productNodeFlowList.size() > 0) {
                for (ProductNodeFlow productNodeFlow : productNodeFlowList) {
                    if (ids.length() > 0) {//该步即不会第一位有逗号，也防止最后一位拼接逗号！
                        ids.append(",");
                    }
                    ids.append(productNodeFlow.getId());
                }
                mapNode.put("deptIds", orgMap.get("id"));
                mapNode.put("processId", ids.toString().split(","));
                listNode = zzProductNodeDao.queryByFlowProcessIds(mapNode);
            }
        }
        model.addAttribute("listNode", listNode);
        return "zzsc/all/stopScOrder";
    }
    /**
     * json查询所有我的生产订单
     *
     * @param params
     * @param request
     * @returnSC_GENERAL_STATE_SCPROORDER_CODE1 orderColumn
     */
    @NLog
    @RequestMapping(value = "/myScOrderJson")
    @ResponseBody
    public DataTableResponse myScOrder(@RequestParam Map params, HttpServletRequest request, Model model) {
        DataTableRequest r = DataTableUtils.getParam(request);
        params.put("page", r.getPage());
        params.put("limit", r.getLength());
        Map fileMap = new HashMap();
        fileMap.put("signTime", "t.sign_time");
        fileMap.put("lastRemarkTime", "lastRemarkTime");//最新备注时间
        OrderHandleUtils.getOrderCol(r, params, fileMap);
        List<Map> list = allorderservice.myScOrderWithPage(params);
        String[] transColum = {"originCode", "status"};
        list = translateUtil.translateList(transColum, list);
        String[] hideColum = {"customerPhone"};//隐藏
        list = desUtil.decryptListMap(hideColum, list);
        CustomerNumberEncryptionUtil.encryptionList(hideColum, list);
        int count = Integer.parseInt(params.get("count").toString());//总条数
        return new DataTableResponse(r.getDraw(), count, count, list, "");
    }

    /**
     * json查询所有部门生产订单
     *
     * @param params
     * @param request
     * @returnSC_GENERAL_STATE_SCPROORDER_CODE1
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    @NLog
    @RequestMapping(value = "/deptScOrderJson")
    @ResponseBody
    public DataTableResponse deptScOrderJson(@RequestParam Map params, HttpServletRequest request, Model model) {
        DataTableRequest r = DataTableUtils.getParam(request);
        params.put("page", r.getPage());
        params.put("limit", r.getLength());
        Map fileMap = new HashMap();
        fileMap.put("signTime", "t.sign_time");
        fileMap.put("lastRemarkTime", "lastRemarkTime");//最新备注时间
        OrderHandleUtils.getOrderCol(r, params, fileMap);
        List<Map> list = allorderservice.deptScOrderWithPage(params);
        String[] transColum = {"originCode", "status"};
        list = translateUtil.translateList(transColum, list);
        String[] hideColum = {"customerPhone"};//隐藏
        list = desUtil.decryptListMap(hideColum, list);
        CustomerNumberEncryptionUtil.encryptionList(hideColum, list);
        int count = Integer.parseInt(params.get("count").toString());//总条数
        return new DataTableResponse(r.getDraw(), count, count, list, "");
    }

    /**
     * json查询所有生产订单
     *
     * @param params
     * @param request
     * @returnSC_GENERAL_STATE_SCPROORDER_CODE1
     */
    @NLog
    @RequestMapping(value = "/allScOrderJson")
    @ResponseBody
    public DataTableResponse allScOrder(@RequestParam Map params, HttpServletRequest request) {
        DataTableRequest r = DataTableUtils.getParam(request);
        params.put("page", r.getPage());
        params.put("limit", r.getLength());
        Map fileMap = new HashMap();
        fileMap.put("signTime", "signTime");
        fileMap.put("lastRemarkTime", "lastRemarkTime");//最新备注时间
        OrderHandleUtils.getOrderCol(r, params, fileMap);
        List<Map> list = allorderservice.allScOrderWithPage(params);
        String[] transColum = {"originCode", "matchingStatus", "status","afterSaleStatus","productHandleResultType"};
        list = translateUtil.translateList(transColum, list);
        String[] hideColum = {"customerPhone"};//隐藏
        list = desUtil.decryptListMap(hideColum, list);
        CustomerNumberEncryptionUtil.encryptionList(hideColum, list);
        int count = Integer.parseInt(params.get("count").toString());//总条数
        return new DataTableResponse(r.getDraw(), count, count, list, "");
    }
    /**
     * 返回修改流程人员页面
     *
     * @return
     */
    @RequestMapping(value = "/update_user_page.html")
    public String updateUserPage(Model model, @RequestParam(value = "ids[]",required = false) List<Long> ids) {
        if(CollectionUtils.isEmpty(ids)){
            throw new ProductOrderExcption("未获取到订单id，请刷新页面重试");
        }
        if(ids.size() == 1){
            model.addAttribute("isShow",false);
            model.addAttribute("productOrder", allorderservice.findOrderById(ids.get(0)));
        }else {
            model.addAttribute("isShow",true);
            model.addAttribute("orderList",zzCompletedOrderService.getCheckCloseAuditOrder(ids));
        }
        return "zzsc/all/update_user_page";
    }

    /**
     * 修改流程人员
     *
     * @param ids              订单id集合
     * @param flowUserId       流程人员ID
     * @return
     */
    @RequestMapping(value = "/update_flow_user.do")
    @ResponseBody
    public DggRestResponse updateFlowUser(@RequestParam(value = "ids[]",required = false) List<Long> ids, Long flowUserId) {
        try {
            //判断是否传递子订单id
            if (ids == null || ids.size() == 0) {
                return getFailResponse("未获取到订单id，请刷新页面重试");
            }
            //判断是否传递子订单id
            if (ids.size() > 10) {
                return getFailResponse("最多只能选择10条数据!");
            }
            if(net.dgg.iboss.base.util.StringUtils.isEmptyObj(flowUserId)){
                return getFailResponse("未获取到流程人员，请刷新页面重试");
            }
            //修改流程人员
            allorderservice.updateFlowUser(ids, flowUserId);
            return getSuccessResponse(null);
        } catch (Exception e) {
            ExceptionUtils.error(e, "/sc/all/update_flow_user.do", ids, flowUserId);
            return getFailResponse("操作失败");
        }

    }

    /**
     * json查询所有已分配生产订单
     *
     * @param params
     * @param request
     * @returnSC_GENERAL_STATE_SCPROORDER_CODE1
     */
    @NLog
    @RequestMapping(value = "/allocatedScOrderJson")
    @ResponseBody
    public DataTableResponse allocatedScOrderJson(@RequestParam Map params, HttpServletRequest request) {
        DataTableRequest r = DataTableUtils.getParam(request);
        params.put("page", r.getPage());
        params.put("limit", r.getLength());
        Map fileMap = new HashMap();
        fileMap.put("allotDate", "allotDate");
        OrderHandleUtils.getOrderCol(r, params, fileMap);
        // 数据权限
        DataAuthDTO dataAuthDTO = dataPermissionAssocService.selectAuthToConfigureRturnOrgIds("zz_zzsc_waitdistrubute");
        params.put("dataAuthDTO", dataAuthDTO);
        params.put("deptAlias", "t");
        params.put("deptColumn", "product_org_id");
        List<Map> list = allorderservice.allocatedScOrderWithPage(params);
        String[] transColum = {"originCode"};
        list = translateUtil.translateList(transColum, list);
        String[] hideColum = {"customerPhone"};//隐藏
        list = desUtil.decryptListMap(hideColum, list);
        CustomerNumberEncryptionUtil.encryptionList(hideColum, list);
        int count = Integer.parseInt(params.get("count").toString());//总条数
        return new DataTableResponse(r.getDraw(), count, count, list, "");
    }

    @RequestMapping(value = "/export", method = RequestMethod.POST)
    @ResponseBody
    public void POIExcel(@RequestParam Map params, HttpServletRequest request, HttpServletResponse response) {
        // 查询数据集合
        List<Map> list = allorderservice.allScOrderWithPage(params);
        String[] transColum = {"status"};
        list = translateUtil.translateList(transColum, list);
        String[] hideColum = {"customerPhone"};//隐藏
        list = desUtil.decryptListMap(hideColum, list);
        CustomerNumberEncryptionUtil.encryptionList(hideColum, list);
        String fileName = "全部生产订单" + ".xls";
        String[] title = {"订单来源", "订单编号", "生产订单编号", "合同编号", "客户", "客户号码", "订单状态", "完成节点", "业务类型", "订单产品", "签单时间", "最新备注", "最新备注时间", "签单商务", "签单部门", "流程人员", "协单人员", "企业名称", "流程部门", "合同金额", "订单来源"};
        String[] key = {"signOrgName", "orderNo", "scProductOrderNo", "contractNo", "customerName", "customerPhone", "status", "latestEndNodeName", "businessProductName", "productName", "signTime", "lastRemark", "lastRemarkTime", "signUserName", "signUserOrgName", "flowUserName", "assistUserName", "companyName", "flowUserOrgName", "money", "signOrgName"};
        ExcelUtil.createN(fileName, title, key, list, response);
    }

    @RequestMapping(value = "/allocatedscorde_export", method = RequestMethod.POST)
    @ResponseBody
    public void POIAllocatedScOrderWithPageExcel(@RequestParam Map params, HttpServletRequest request, HttpServletResponse response) {
        // 查询数据集合
        // 数据权限
        DataAuthDTO dataAuthDTO = dataPermissionAssocService.selectAuthToConfigureRturnOrgIds("zz_zzsc_waitdistrubute");
        params.put("dataAuthDTO", dataAuthDTO);
        params.put("deptAlias", "t");
        params.put("deptColumn", "product_org_id");
        List<Map> list = allorderservice.allocatedScOrderWithPage(params);
        for (Map map : list) {
            if (map.get("allotWay").toString().equals(ScProductConstant.ALLOT_TO_PRODUCT_USER)) {
                map.put("flowUserName", map.get("productUserName"));
                map.put("flowUserOrgName", map.get("productUserOrgName"));
            }
        }
        String[] transColum = {"status"};
        list = translateUtil.translateList(transColum, list);
        String[] hideColum = {"customerPhone"};//隐藏
        list = desUtil.decryptListMap(hideColum, list);
        CustomerNumberEncryptionUtil.encryptionList(hideColum, list);
        String fileName = "已分配" + ".xls";
        String[] title = {"订单来源", "订单编号", "生产订单编号", "合同编号", "客户", "客户号码", "业务类型", "订单产品", "是否需办理", "分配时间", "分配人", "流程人员", "流程部门"};
        String[] key = {"signOrgName", "orderNo", "scProductOrderNo", "contractNo", "customerName", "customerPhone", "businessProductName", "productName", "isNeedDispose", "allotDate", "allotUserName", "flowUserName", "flowUserOrgName"};
        ExcelUtil.createN(fileName, title, key, list, response);
    }


    /**
     * <p>@Description 团队待分配/p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/28 0028 11:03 创建时间</p>
     * <p>@return</p>
     */
    @NLog
    @RequestMapping(value = "/team_allot_dept_product_order")
    public String teamAllotDeptProductOrder(@RequestParam Map params, Model model) {
        List<ProductNode> listNode = new ArrayList<>();
        //查询出当前登陆人的事业部id
        Map orgMap = zzCommonMangerExtService.findBusDeptById(sessionManager.getCurrentUser().getOrgId());
        if (orgMap != null && orgMap.size() != 0) {
            Map map = new HashMap();
            Map mapNode = new HashMap();
            StringBuilder ids = new StringBuilder();
            //根据事业部的id查询出改事业部配置流程节点ids
            map.put("deptIds", orgMap.get("id"));
            if (null == map.get("orderColumn")) {
                map.put("orderDir", "desc");
                map.put("orderColumn", "updateTime");
            }
            List<ProductNodeFlow> productNodeFlowList = zzProductNodeFlowDao.query(map);
            if (productNodeFlowList.size() > 0) {
                for (ProductNodeFlow productNodeFlow : productNodeFlowList) {
                    if (ids.length() > 0) {//该步即不会第一位有逗号，也防止最后一位拼接逗号！
                        ids.append(",");
                    }
                    ids.append(productNodeFlow.getId());
                }
                mapNode.put("deptIds", orgMap.get("id"));
                mapNode.put("processId", ids.toString().split(","));
                listNode = zzProductNodeDao.queryByFlowProcessIds(mapNode);
            }
        }
        model.addAttribute("listNode", listNode);
        model.addAttribute("TIME_OUT", ScProductConstant.TIME_OUT);
        model.addAttribute("isTimeOUt", params.get("isTimeOUt"));
        return "zzsc/team/team_allot_dept_product_order";
    }

    /**
     * <p>@Description 团队待分配(超期)数据</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/28 0028 11:03 创建时间</p>
     * <p>@return</p>
     */
    @NLog
    @RequestMapping(value = "/team_allot_dept_product_order_data")
    @ResponseBody
    public DataTableResponse teamAllotDeptProductOrderData(@RequestParam Map params, HttpServletRequest request) {
        DataTableRequest r = DataTableUtils.getParam(request);
        params.put("page", r.getPage());
        params.put("limit", r.getLength());
        List<Map> list = allorderservice.teamAllotDeptProductOrderData(params);
        String[] transColum = {"originCode", "status"};
        list = translateUtil.translateList(transColum, list);
        String[] hideColum = {"customerPhone"};//隐藏
        list = desUtil.decryptListMap(hideColum, list);
        CustomerNumberEncryptionUtil.encryptionList(hideColum, list);
        int count = Integer.parseInt(params.get("count").toString());//总条数
        return new DataTableResponse(r.getDraw(), count, count, list, "");
    }


    /**
     * <p>@Description 团队待接收</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/28 0028 11:03 创建时间</p>
     * <p>@return</p>
     */
    @NLog
    @RequestMapping(value = "/team_receive_dept_product_order")
    public String teamReceiveDeptProductOrder(@RequestParam Map params, Model model) {
        List<ProductNode> listNode = new ArrayList<>();
        //查询出当前登陆人的事业部id
        Map orgMap = zzCommonMangerExtService.findBusDeptById(sessionManager.getCurrentUser().getOrgId());
        if (orgMap != null && orgMap.size() != 0) {
            Map map = new HashMap();
            Map mapNode = new HashMap();
            StringBuilder ids = new StringBuilder();
            //根据事业部的id查询出改事业部配置流程节点ids
            map.put("deptIds", orgMap.get("id"));
            if (null == map.get("orderColumn")) {
                map.put("orderDir", "desc");
                map.put("orderColumn", "updateTime");
            }
            List<ProductNodeFlow> productNodeFlowList = zzProductNodeFlowDao.query(map);
            if (productNodeFlowList.size() > 0) {
                for (ProductNodeFlow productNodeFlow : productNodeFlowList) {
                    if (ids.length() > 0) {//该步即不会第一位有逗号，也防止最后一位拼接逗号！
                        ids.append(",");
                    }
                    ids.append(productNodeFlow.getId());
                }
                mapNode.put("deptIds", orgMap.get("id"));
                mapNode.put("processId", ids.toString().split(","));
                listNode = zzProductNodeDao.queryByFlowProcessIds(mapNode);
            }
        }
        model.addAttribute("listNode", listNode);
        model.addAttribute("TIME_OUT", ScProductConstant.TIME_OUT);
        model.addAttribute("isTimeOUt", params.get("isTimeOUt"));
        return "zzsc/team/team_receive_dept_product_order";
    }

    /**
     * <p>@Description 团队待接收数据</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/28 0028 11:03 创建时间</p>
     * <p>@return</p>
     */
    @NLog
    @RequestMapping(value = "/team_receive_dept_product_order_data")
    @ResponseBody
    public DataTableResponse teamReceiveDeptProductOrderData(@RequestParam Map params, HttpServletRequest request) {
        DataTableRequest r = DataTableUtils.getParam(request);
        params.put("page", r.getPage());
        params.put("limit", r.getLength());
        List<Map> list = allorderservice.teamReceiveDeptProductOrderData(params);
        String[] transColum = {"originCode", "status"};
        list = translateUtil.translateList(transColum, list);
        String[] hideColum = {"customerPhone"};//隐藏
        list = desUtil.decryptListMap(hideColum, list);
        CustomerNumberEncryptionUtil.encryptionList(hideColum, list);
        int count = Integer.parseInt(params.get("count").toString());//总条数
        return new DataTableResponse(r.getDraw(), count, count, list, "");
    }


    /**
     * <p>@Description 跳转到生产统计页面</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/11/7 0007 10:13 创建时间</p>
     * <p>@return</p>
     */
    @RequestMapping("/sc_order_count")
    @NLog
    public String scOrderCount() {

        return "zzsc/all/sc_order_count";
    }


    /**
     * <p>@Description 获取生产统计数据</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/11/7 0007 10:25 创建时间</p>
     * <p>@return</p>
     */
    @RequestMapping("/sc_order_count_data")
    @NLog
    @ResponseBody
    public DggRestResponse scOrderCountData(@RequestParam Map params) {
        Map map = allorderservice.scOrderCountData(params);
        return this.getSuccessResponse(map);
    }

    /**
     * <p>@Description 导出</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/11/7 0007 15:28 创建时间</p>
     * <p>@return</p>
     */
    @RequestMapping("/export_order_count_data")
    @NLog
    public void exportOrderCountData(@RequestParam Map params, HttpServletResponse response) {
        try {
            String fileName = "资质IBOSS生产系统数据统计_" + DateUtils.dateString(new Date(), "yyyyMMddHHmm") + ".xlsx";
            List<OrderCountVo> orderCountVos = allorderservice.exportOrderCountData(params);
            ExcelUtils.writeToFile(orderCountVos, null, fileName, response, OrderCountVo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 报表统计-生成订单数据
     *
     * @param model
     * @param status 状态
     * @return
     */
    @NLog
    @RequestMapping(value = "/scOrderData")
    public String scOrderData(Model model, String status) {
        return "zzsc/all/sc_order_data";
    }

    /**
     * 生产订单数据导出
     *
     * @param params
     * @return
     */
    @RequestMapping("export_order_data")
    public void exportOrderData(@RequestParam Map params, HttpServletResponse response) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            UserEntity userEntity = sessionManager.getCurrentUser();
            Map orgMap = commonMangerExtService.findBusDeptById(userEntity.getOrgId());
            if (null == params.get("deptId")) {
                params.put("deptId", orgMap.get("id"));
            }

            if (null == params.get("startTime")) {
                Calendar c = Calendar.getInstance();
                c.add(Calendar.MONTH, 0);
                c.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
                String first = format.format(c.getTime());
                params.put("startTime", first + " 00:00:00");
            } else {
                params.put("startTime", params.get("startTime").toString() + " 00:00:00");
            }
            if (null == params.get("endTime")) {
                Date date = new Date();
                SimpleDateFormat formatNow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                params.put("endTime", formatNow.format(date));
            } else {
                params.put("endTime", params.get("endTime").toString() + " 23:59:59");
            }

            String fileName = "生产订单数据_" + DateUtils.dateString(new Date(), "yyyyMMddHHmm") + ".xlsx";
            List<OrderDataVo> dataList = orgOrderService.findByParamsList(params);
            ExcelUtils.writeToFile(dataList, null, fileName, response, OrderDataVo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * @Author zsx
     * @Date 2018-11-13 10:11:55
     * @Description 更具订单编号查询订单id
     * @param scOrderNo 订单号
     */
    @NLog
    @RequestMapping("/getScOrder")
    @ResponseBody
    public DggRestResponse getScOrder(@RequestParam String scOrderNo) {
        List<Long> orderIds = orgOrderService.findOrderIdByScOrderNo(scOrderNo);
        if (null == orderIds || orderIds.size() == 0) {
            return this.getFailResponse("不存在可使用证书的订单->" + scOrderNo);
        }
        return this.getSuccessResponse(orderIds);
    }

    /**
     * <p>@Description 全部部门的导出</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/31 0031 16:19 创建时间</p>
     * <p>@return</p>
     */
    @RequestMapping("/export_product_order")
    public void exportSczzAbnormal(@RequestParam Map params, HttpServletResponse response) {
        try {
            String fileName = "部门生产订单_" + DateUtils.dateString(new Date(), "yyyyMMddHHmm") + ".xlsx";
            UserEntity userEntity = sessionManager.getCurrentUser();
            params.put("userEntity", userEntity.getId()); //当前登录人
            if (StringUtils.isNotEmpty(params.get("customerPhone"))) {
                params.put("customerPhone", desUtil.encrypt(params.get("customerPhone").toString()));
            }
            //获取判断界面展示内容的key
            getAcquisitionConditions(params);
            List<OrgOrderVo> dataList = allorderservice.findExportProductOrder(params);
            ExcelUtils.writeToFile(dataList, null, fileName, response, OrgOrderVo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * <p>@Description 获取判断界面展示内容的key</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/21 0027 15:20 创建时间</p>
     * <p>@return</p>
     */
    private void getAcquisitionConditions(Map<String, Object> map) {
        String type = null == map.get("type") ? "" : map.get("type").toString();
        if ("toDay".equals(type)) { //今日待跟进
            map.put("toDay", "toDay");
        } else if ("currentDay".equals(type)) { //新增办理
            map.put("currentDay", "currentDay");
        } else if ("hasOverDue".equals(type)) { //超期跟进
            map.put("hasOverDue", "hasOverDue");
        } else if ("nodeOverDue".equals(type)) { //节点超期
            map.put("nodeOverDue", ScProductConstant.TIME_OUT);
        } else if ("proOverDue".equals(type)) { //订单超期
            map.put("proOverDue", ScProductConstant.TIME_OUT);
        } else {
            map.put("all", ScProductConstant.SC_ORDER_IN_PROCESS); //全部
        }
    }

    /**
     * json查询终止生产订单
     *
     * @param params
     * @param request
     * @returnSC_GENERAL_STATE_SCPROORDER_CODE1
     */
    @NLog
    @RequestMapping(value = "/stopScOrderJson")
    @ResponseBody
    public DataTableResponse stopScOrderJson(@RequestParam Map params, HttpServletRequest request) {
        DataTableRequest r = DataTableUtils.getParam(request);
        params.put("page", r.getPage());
        params.put("limit", r.getLength());
        Map fileMap = new HashMap();
        fileMap.put("signTime", "signTime");
        fileMap.put("lastRemarkTime", "lastRemarkTime");//最新备注时间
        OrderHandleUtils.getOrderCol(r, params, fileMap);
        params.put("orderStatus",ScProductConstant.SC_ORDER_STOP);
        params.put("dataAuthority","ZZSC_STOP_ORDER");
        List<Map> list = allorderservice.stopScOrderWithPage(params);
        String[] transColum = {"originCode", "status"};
        list = translateUtil.translateList(transColum, list);
        String[] hideColum = {"customerPhone"};//隐藏
        list = desUtil.decryptListMap(hideColum, list);
        CustomerNumberEncryptionUtil.encryptionList(hideColum, list);
        int count = Integer.parseInt(params.get("count").toString());//总条数
        return new DataTableResponse(r.getDraw(), count, count, list, "");
    }

    @RequestMapping(value = "/stopExport", method = RequestMethod.POST)
    @ResponseBody
    public void stopExport(@RequestParam Map params, HttpServletRequest request, HttpServletResponse response) {
        params.put("orderStatus",ScProductConstant.SC_ORDER_STOP);
        params.put("dataAuthority","ZZSC_STOP_ORDER");
        List<Map> list = allorderservice.stopScOrderWithPage(params);
        /*String[] hideColum = {"customerPhone"};//隐藏
        list = desUtil.decryptListMap(hideColum, list);
        CustomerNumberEncryptionUtil.encryptionList(hideColum, list);*/
        String fileName = "中止状态生产订单" + ".xls";
        String[] title = {"订单来源", "订单编号", "生产订单编号", "业务类型", "订单产品", "当前完成节点", "节点最后更新时间", "暂停时间", "预计开始时间", "最新备注", "签单商务", "合同金额", "流程人员", "协单人员", "企业名称"};
        String[] key = {"signOrgName", "orderNo", "scProductOrderNo", "businessProductName", "productName", "latestEndNodeName", "latestEndNodeTime", "startSuspendTime", "expectOpenDate", "lastRemark", "signUserName", "money", "flowUserName", "assistUserName", "companyName"};
        ExcelUtil.createN(fileName, title, key, list, response);
    }

    /**
     * 客户订单管理页面
     *
     * @param model
     * @return
     */
    @NLog
    @RequestMapping(value = "/customerScOrder")
    public String customerScOrder(Model model) {
        return "zzsc/all/customerScOrder";
    }
    /**
     * json查询客户订单
     *
     * @param params
     * @param request
     * @returnSC_GENERAL_STATE_SCPROORDER_CODE1
     */
    @NLog
    @RequestMapping(value = "/customerScOrderJson")
    @ResponseBody
    public DataTableResponse customerScOrderJson(@RequestParam Map params, HttpServletRequest request) {
        DataTableRequest r = DataTableUtils.getParam(request);
        params.put("page", r.getPage());
        params.put("limit", r.getLength());
        List<Map> list = allorderservice.customerScOrderWithPage(params);
        String[] transColum = {"originCode", "status"};
        list = translateUtil.translateList(transColum, list);
        String[] hideColum = {"customerPhone"};//隐藏
        list = desUtil.decryptListMap(hideColum, list);
        CustomerNumberEncryptionUtil.encryptionList(hideColum, list);
        int count = Integer.parseInt(params.get("count").toString());//总条数
        return new DataTableResponse(r.getDraw(), count, count, list, "");
    }

    /**
     * 导出客户订单报表
     * @param params
     * @param request
     * @param response
     */
    @RequestMapping(value = "/customerExport", method = RequestMethod.POST)
    @ResponseBody
    public void customerExport(@RequestParam Map params, HttpServletRequest request, HttpServletResponse response) {
        List<Map> list = allorderservice.customerScOrderWithPage(params);
        String[] hideColum = {"customerPhone"};//隐藏
        list = desUtil.decryptListMap(hideColum, list);
        CustomerNumberEncryptionUtil.encryptionList(hideColum, list);
        String fileName = "客户生产订单" + ".xls";
        String[] title = {"客户编号", "客户名称", "企业名称", "客户电话", "订单总金额", "订单总量", "办理中", "已暂停", "已中止", "退单待审核", "退单驳回", "已退单", "生产完结", "已结项", "办理中节点超期单数","订单超期单数"};
        String[] key = {"customerNo", "customerName", "companyName", "customerPhone", "money", "totleNum", "inprocessCount", "suspendCount", "orderStopCount", "chargeBackingCount", "chargeBackBhCount", "chargeBackedCount", "orderOverCount", "orderJuncttonCount", "nodeStatus","orderStatus"};
        ExcelUtil.createN(fileName, title, key, list, response);
    }

    /**
     * 客户订单详情页面
     *
     * @param model
     * @return
     */
    @NLog
    @RequestMapping(value = "/findCustomerInfo")
    public String findCustomerInfo(Model model,String customerNo,Long customerId) {

        CustomerDTO customerDTO = ucApiService.findCustomerById(customerId);
        if (customerDTO != null) {
            String[] dtoColumn = {"sex", "origin", "businessArea", "customerType"};
            customerDTO = translateUtil.translateObject(dtoColumn, customerDTO);
            String number = this.desUtil.decrypt(customerDTO.getNumber());//解密电话号码
            customerDTO.setNumber(number);
        }

        Map map = new HashMap();
        map.put("customerNo",customerNo);
        List<Map> list = allorderservice.findCustomerInfo(map);
        String[] hideColum = {"customerPhone"};//隐藏
        list = desUtil.decryptListMap(hideColum, list);
        CustomerNumberEncryptionUtil.encryptionList(hideColum, list);
        model.addAttribute("customerInfoList",list);
        model.addAttribute("customer",customerDTO);
        return "zzsc/all/customerScOrderInfo";
    }
}
